package com.longfa.ojbackendjudgeservice.message;

import com.longfa.ojbackendjudgeservice.service.JudgeService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * ClassName: MyMessageConsumer
 * Package: com.longfa.ojbackendjudgeservice.message
 * Description:
 *
 * @Author:
 * @Create: 2024/5/4 - 14:33
 * @Version: v1.0
 */
@Component
@Slf4j
public class MyMessageConsumer {

    @Resource
    private JudgeService judgeService;


    // 指定程序监听的消息队列和确认机制

    @SneakyThrows
    @RabbitListener(queues = {"oj_queue"}, ackMode = "MANUAL")
    public void receiveMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
//        log.info("receive message: {}", message);
        long questionSubmitId = Long.parseLong(message);
        //在这里还可以进行一些错误处理，如拒绝消息，将消息放入死信队列
        try {
            judgeService.doJudge(questionSubmitId);
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            log.error("judge error: {}", e.getMessage());
            // todo 设置重试等
            // 出现异常拒绝消息，重新将消息放回队列
//            channel.basicNack(deliveryTag, false, true);
            // 建议：出现异常之后，将消息放回死信队列。       这里我把重新放回队列设置为 false。防止消息一直异常一直重新放回队列，消耗性能
            channel.basicNack(deliveryTag, false, false);
        }
    }
}
